import winston from 'winston'

// 创建日志记录器
export const logger = winston.createLogger({
    level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
    format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.json()
    ),
    transports: [
        new winston.transports.Console({
            format: winston.format.combine(
                winston.format.colorize(),
                winston.format.simple()
            )
        }),
        new winston.transports.File({ filename: 'error.log', level: 'error' }),
        new winston.transports.File({ filename: 'combined.log' })
    ]
})

// 添加请求日志中间件
export const requestLogger = (req: any, res: any, next: any) => {
    const start = Date.now()

    res.on('finish', () => {
        const duration = Date.now() - start
        logger.info({
            method: req.method,
            url: req.url,
            status: res.statusCode,
            duration,
            ip: req.ip
        })
    })

    next()
}

// 错误日志中间件
export const errorLogger = (err: any, req: any, res: any, next: any) => {
    logger.error({
        message: err.message,
        stack: err.stack,
        method: req.method,
        url: req.url,
        ip: req.ip
    })

    next(err)
}